package com.itedge.solutionmanager.service.task.impl.customer;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.activiti.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itedge.solutionmanager.domain.impl.ContactPerson;
import com.itedge.solutionmanager.domain.impl.Customer;
import com.itedge.infrastructure.service.domain.IProcessEntityService;
import com.itedge.infrastructure.service.task.ITaskService;
import com.itedge.infrastructure.service.taskdata.ITaskDataEntityService;
import com.itedge.solutionmanager.taskdata.impl.customer.RemoveContactsTaskData;

@Service
public class RemoveContactsTaskService implements ITaskService<RemoveContactsTaskData, Customer> {

    @Autowired
    protected TaskService taskService;
    @Autowired
    private IProcessEntityService<Customer> customerService;
    @Autowired
    private ITaskDataEntityService<RemoveContactsTaskData> removeContactsTaskDataService;
	
	@Override
	@Transactional
	public void completeTask(String taskId, Customer linkedObject,
			RemoveContactsTaskData taskData, String user) {
    	removeContactsTaskDataService.merge(taskData);
    	List<String> removedIdsList = Arrays.asList(taskData.getRemovedContactsIds().split(","));
    	Set<ContactPerson> contactsToRemove = new HashSet<ContactPerson>();
    	for (ContactPerson p : linkedObject.getContactPersons()) {
    		// contact is in removed list
            if (removedIdsList.contains(p.getId().toString())) {
            	contactsToRemove.add(p);
            }
    	}
    	linkedObject.removeContactPersons(contactsToRemove);
    	customerService.merge(linkedObject);
    	taskService.setAssignee(taskId, user);
    	taskService.complete(taskId);	
	}

}
